#include <iostream>
#include <event2/event.h>
#include <event2/http.h>
#include <event2/buffer.h>
#include <event2/util.h>
#include <event2/event_struct.h>
#include <cstring>
#include <pthread.h>
#include <unistd.h>
#include <event2/thread.h>
#include <signal.h>
#include <vector>
#include <string>
#include <fstream>
std::string get_cmd_type(const int cmd_type){
    std::string cmdtype;
    switch (cmd_type) {
            case EVHTTP_REQ_GET: cmdtype = "GET"; break;
            case EVHTTP_REQ_POST: cmdtype = "POST"; break;
            case EVHTTP_REQ_HEAD: cmdtype = "HEAD"; break;
            case EVHTTP_REQ_PUT: cmdtype = "PUT"; break;
            case EVHTTP_REQ_DELETE: cmdtype = "DELETE"; break;
            case EVHTTP_REQ_OPTIONS: cmdtype = "OPTIONS"; break;
            case EVHTTP_REQ_TRACE: cmdtype = "TRACE"; break;
            case EVHTTP_REQ_CONNECT: cmdtype = "CONNECT"; break;
            case EVHTTP_REQ_PATCH: cmdtype = "PATCH"; break;
            default: cmdtype = "unknown"; break;
    }
    return cmdtype;
}
// 解析 multipart/form-data 请求体
void parse_multipart_form_data(const char *body_data, size_t body_len, const std::string &boundary) {
    std::string body(body_data, body_len);
    std::string delimiter = "--" + boundary;
    std::vector<std::string> parts;

    // 按 boundary 分割请求体
    size_t pos = 0;
    while ((pos = body.find(delimiter, pos)) != std::string::npos) {
        pos += delimiter.length();
        if (body.substr(pos, 2) == "--") break; // 结束边界
        size_t end = body.find(delimiter, pos);
        if (end == std::string::npos) break;
        parts.push_back(body.substr(pos, end - pos - 2)); // 去掉末尾的 \r\n
        pos = end;
    }

    // 解析每个部分
    for (const auto &part : parts) {
        size_t header_end = part.find("\r\n\r\n");
        if (header_end == std::string::npos) continue;

        std::string headers = part.substr(0, header_end);
        std::string content = part.substr(header_end + 4);

        // 解析字段名和文件名
        std::string name, filename;
        size_t name_pos = headers.find("name=\"");
        if (name_pos != std::string::npos) {
            name_pos += 6;
            size_t name_end = headers.find("\"", name_pos);
            name = headers.substr(name_pos, name_end - name_pos);
        }
        size_t file_pos = headers.find("filename=\"");
        if (file_pos != std::string::npos) {
            file_pos += 10;
            size_t file_end = headers.find("\"", file_pos);
            filename = headers.substr(file_pos, file_end - file_pos);
        }

        if (!filename.empty()) {
            // 处理文件上传
            std::ofstream file(filename, std::ios::binary);
            if (file.is_open()) {
                file.write(content.data(), content.size());
                std::cout << "File saved: " << filename << " (size: " << content.size() << " bytes)" << std::endl;
            } else {
                std::cerr << "Failed to save file: " << filename << std::endl;
            }
        } else {
            // 处理普通字段
            std::cout << "Field [" << name << "]: " << content << std::endl;
        }
    }
}
void get_post_params(struct evhttp_request *req){
    // 获取请求头

    // 获取 Content-Type 并检查是否为 multipart/form-data
    struct evkeyvalq *headers = evhttp_request_get_input_headers(req);
    const char *content_type = evhttp_find_header(headers, "Content-Type");
    if (!content_type || !strstr(content_type, "multipart/form-data")) {
        evhttp_send_error(req, HTTP_BADREQUEST, "Expected multipart/form-data");
        return;
    }

    // 提取 boundary
    const char *boundary_start = strstr(content_type, "boundary=");
    if (!boundary_start) {
        evhttp_send_error(req, HTTP_BADREQUEST, "Missing boundary");
        return;
    }
    std::string boundary(boundary_start + 9); // 跳过 "boundary="

    // 获取请求体
    struct evbuffer *input_buffer = evhttp_request_get_input_buffer(req);
    size_t body_len = evbuffer_get_length(input_buffer);
    char *body_data = new char[body_len + 1];
    evbuffer_copyout(input_buffer, body_data, body_len);
    body_data[body_len] = '\0';

    // 解析 multipart/form-data
    parse_multipart_form_data(body_data, body_len, boundary);

}
// HTTP请求回调函数
void http_request_handler(struct evhttp_request *req, void *ctx) {

    const int method = evhttp_request_get_command(req);
    std::cout << "Received " << get_cmd_type(method) << " request." << std::endl;
    if(method == EVHTTP_REQ_POST){
        get_post_params(req);
    }

    // 创建一个响应缓冲区
    struct evbuffer *response_buffer = evbuffer_new();
    if (!response_buffer) {
        std::cerr << "Failed to create response buffer" << std::endl;
        evhttp_send_error(req, HTTP_SERVUNAVAIL, "Server error");
        return;
    }

    // 设置响应内容
    evbuffer_add_printf(response_buffer, "Hello, World!\n");

    // 发送响应
    evhttp_send_reply(req, HTTP_OK, "OK", response_buffer);

    // 释放缓冲区
    evbuffer_free(response_buffer);
}

int main() {
    // 初始化libevent
    if(signal(SIGPIPE,SIG_IGN) == SIG_ERR){
        return -1;
    }
    struct event_base *base = event_base_new();
    if (!base) {
        std::cerr << "Failed to create event base" << std::endl;
        return 1;
    }
    evthread_use_pthreads();
    // 创建HTTP服务器
    struct evhttp *http_server = evhttp_new(base);
    if (!http_server) {
        std::cerr << "Failed to create HTTP server" << std::endl;
        return 1;
    }

    // 绑定到本地地址和端口
    if (evhttp_bind_socket(http_server, "0.0.0.0", 8080) != 0) {
        std::cerr << "Failed to bind to port 8080" << std::endl;
        return 1;
    }

    // 设置请求处理回调函数
    evhttp_set_gencb(http_server, http_request_handler, nullptr);

    std::cout << "HTTP server started on port 8080" << std::endl;

    // 进入事件循环
    event_base_dispatch(base);

    // 清理资源
    evhttp_free(http_server);
    event_base_free(base);

    return 0;
}
